package com.room.search.service;

import com.room.search.constant.UserConstants;
import com.room.search.core.page.TableDataInfo;
import com.room.search.domain.RoomDictData;
import com.room.search.repository.RoomDictDataRepository;
import com.room.search.response.RoomResult;
import com.room.search.service.dto.RoomDictDataDTO;
import com.room.search.service.mapper.RoomDictDataMapper;
import com.room.search.util.DictUtils;
import com.room.search.util.PageUtils;
import com.room.search.util.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * By   : ghd.bright
 * Time : 2022/3/3
 * Description:
 */

@Service
public class RoomDictDataService {

    private final RoomDictDataRepository roomDictDataRepository;
    private final RoomDictDataMapper roomDictDataMapper;


    public RoomDictDataService(RoomDictDataRepository roomDictDataRepository, RoomDictDataMapper roomDictDataMapper) {
        this.roomDictDataRepository = roomDictDataRepository;
        this.roomDictDataMapper = roomDictDataMapper;
    }

    /**
     * 根据type查询对应的data
     */
    public RoomResult getDataFromType(String dictType) {

        List<RoomDictData> dictData = DictUtils.getDictCache(dictType);
        if (!dictData.isEmpty()) {
            return RoomResult.success(dictData);
        }

        List<RoomDictData> data = roomDictDataRepository.findAllByType(dictType);
        if (StringUtils.isNotEmpty(data)) {
            DictUtils.setDictCache(dictType, data);
            return RoomResult.success(data);
        }
        return null;
    }

    /**
     * 分页查询所有的dicData
     */
    public TableDataInfo list(RoomDictDataDTO dto) {
        Pageable pageable = PageUtils.startPage();
        Page<RoomDictData> all = roomDictDataRepository.findAll((root, query, c) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (dto.getDictLabel() != null) {
                predicates.add(c.equal(root.get("dict_label"), dto.getDictLabel()));
            }

            if (dto.getType() != null) {
                predicates.add(c.equal(root.get("type"), dto.getType()));
            }

            if (dto.getStatus() != null) {
                predicates.add(c.equal(root.get("status"), dto.getStatus()));
            }

            return query.where(predicates.toArray(new Predicate[0])).getRestriction();
        }, pageable);
        return TableDataInfo.getTableDataInfo(all);
    }

    public RoomDictDataDTO selectDictDataById(Long dictCode) {
        return roomDictDataRepository.findById(dictCode).map(roomDictDataMapper::toDto).orElse(null);
    }

    /**
     * 新增
     */
    public RoomResult insertDictData(RoomDictDataDTO dto) {
        RoomDictData roomDictData = roomDictDataMapper.toEntity(dto);
        if (UserConstants.NOT_UNIQUE.equals(checkDictDataIsUnique(dto))) {
            return RoomResult.error("新增失败，此字典数据已存在");
        }
        roomDictData.setCreateBy("admin");
        roomDictData.setCreateTime(new Date());
        roomDictDataRepository.save(roomDictData);
        return RoomResult.success("新增成功");
    }

    private String checkDictDataIsUnique(RoomDictDataDTO dto) {
        RoomDictData dictData = roomDictDataRepository.findByTypeAndDictLabel(dto.getType(), dto.getDictLabel()).orElse(null);
        if (dictData != null) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 修改data
     */
    public RoomResult updateDictData(RoomDictDataDTO dto) {
        RoomDictData roomDictData = roomDictDataMapper.toEntity(dto);
        if (UserConstants.NOT_UNIQUE.equals(checkDictDataIsUnique(dto))) {
            return RoomResult.error("修改失败，此字典数据已存在");
        }
        roomDictData.setUpdateTime(new Date());
        roomDictData.setUpdateBy("admin");
        roomDictDataRepository.save(roomDictData);
        return RoomResult.success("修改成功");
    }

    /**
     * 批量删除dictData
     */
    public RoomResult deleteDictDataByIds(Long[] dictCodes) {
        roomDictDataRepository.deleteAllById(Arrays.asList(dictCodes.clone()));
        return RoomResult.success("删除成功");
    }
}
